<template>
  <div class="muban">
    <el-button-group>
      <el-button
        size="small"
        class="button-email"
        type="primary"
        @click="handleSetting">邮箱配置</el-button>
      <el-button
        size="small"
        class="button-email"
        type="primary"
        @click="saveDrafts">存草稿</el-button>
    </el-button-group>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="80px"
      class="demo-ruleForm">
      <el-form-item label="收件人" prop="user" class="contacts">
        <el-input v-model="ruleForm.user" placeholder="填写邮箱地址,例如123456789@qq.com"></el-input>
        <el-button
          type="primary"
          plain
          class="contacts_button"
          @click="handleContactsClick">选择更多收件人</el-button>
      </el-form-item>
      <el-form-item label="主题" prop="title" class="upLoad">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item class="upLoad">
        <el-upload
          class="upload-demo"
          action="http://192.168.36.14:8080/tool/eMail/uploadFile"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :before-remove="beforeRemove"
          :show-file-list="true"
          multiple
          :limit="5"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button class="upload-button" type="text" icon="el-icon-paperclip">附件上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <quill-editor
          :content="ruleForm.content"
          :isShowToolbar="isShowToolbar"
          @onEditorChange="onEditorChange"></quill-editor>
      </el-form-item>
      <!-- 发送按钮 -->
      <el-form-item>
          <el-button
            size="small"
            type="primary"
            @click="submitForm">立即发送</el-button>
          <el-button
            size="small"
            @click="submitFormTimed">定时发送</el-button>
        </el-form-item>
    </el-form>
    <!-- 邮箱配置弹框 -->
    <settingDialog ref="settingDialog"></settingDialog>
    <!-- 联系人弹框 -->
    <el-dialog
      title="联系人"
      :visible.sync="contactsDialogVisible"
      width="40%">
      <el-tree
        :data="data"
        node-key="id"
        :props="defaultProps"
        @check="handleNodeClick"
        ref="tree"
        show-checkbox
        :default-expand-all="true"
        :check-strictly="true"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="contactsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="contactsDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  sendEmailSetting,
  saveDrafts,
  getDraftsDataByid
} from '@/api/email/setting'
import QuillEditor from '@/components/QuillEditor'
import settingDialog from './setting.vue'
export default {
  name: 'muBan',
  data() {
    // 邮箱格式验证
    // let validateEmail = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请正确填写邮箱'))
    //   } else {
    //     if (value !== '') {
    //       let reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    //       if (!reg.test(value)) {
    //         callback(new Error('请输入有效的邮箱'))
    //       }
    //     }
    //     callback()
    //   }
    // }
    return {
      ruleForm: {
        user: '',
        title: '',
        content: ''
      },
      rules: {
        // user: [
        //   { required: true, message: '请填入入收件人', trigger: 'blur' }
        //   // { validator: validateEmail, trigger: 'blur' }
        // ]
      },
      dialogVisible: false,
      contactsDialogVisible: false,
      isShowToolbar: true,
      fileList: [],
      filListUpload: [],
      id: '',
      data: [{
        id: '1',
        label: '1',
        address: '1636794245@qq.com',
        children: [{
          id: '2',
          label: '2',
          address: '1343128728@qq.com',
          children: [{
            id: '3',
            label: '1',
            address: '1636794245@qq.com'
          }]
        }]
      }, {
        id: '4',
        label: '2',
        address: '1636794245@qq.com',
        children: [{
          id: '5',
          label: '1',
          address: '1343128728@qq.com',
          children: [{
            id: '6',
            label: '1',
            address: '1636794245@qq.com'
          }]
        }]
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      contactsArr: []
      // dataData: {}
    }
  },
  created() {
    this.id = this.$route.query.id
    if (this.id !== undefined) {
      getDraftsDataByid(this.id).then((res) => {
        let data = res.data
        this.ruleForm = data
        let arr = this.evil(data.fileUrl)
        // if (arr === [] || arr[0].name === '') {
        if (arr === []) {
          this.fileList = []
        } else {
          this.fileList = arr
        }
      })
    }
    // let data = this.$route.query
    // this.id = data.id
    // if (this.id !== undefined) {
    //   this.ruleForm = data
    //   let arr = this.evil(data.fileUrl)
    //   if (arr === [] || arr[0].name === '') {
    //     this.fileList = []
    //   } else {
    //     this.fileList = arr
    //   }
    // }
  },
  components: {
    QuillEditor,
    settingDialog
  },
  methods: {
    // 发送邮件按钮
    submitForm() {
      if (this.ruleForm.content) {
        var content = this.ruleForm.content.replace(/class="ql-align-right"/g, 'style="text-align: right"')
          .replace(/class="ql-align-center"/g, 'style="text-align: center"')
          .replace(/class="ql-indent-1"/g, 'style="text-indent: 1rem"')
          .replace(/class="ql-align-right ql-direction-rtl"/g, 'style="text-align: right"')
          .replace(/class="ql-size-small"/g, 'style="font-size: 10px"')
          .replace(/class="ql-size-large"/g, 'style="font-size: 18px"')
          .replace(/class="ql-size-huge"/g, 'style="font-size: 32px"')
          // .replace(/\s/g, '&nbsp;')
      }
      const data = {
        user: this.ruleForm.user,
        title: this.ruleForm.title,
        content: content,
        fileList: this.fileList
      }
      sendEmailSetting(data).then((res) => {
        if (res.code === 200) {
          this.ruleForm = {}
          this.fileList = []
          this.ruleForm.content = ''
          this.$refs.tree.setCheckedKeys([])
        }
      })
    },
    // 发送邮件，定时按钮
    submitFormTimed() {
      alert('定时发送')
    },
    // 富文本绑值
    onEditorChange(val) {
      this.ruleForm.content = val.html
    },
    // 附件上传删除
    handleRemove(file2, fileList2) {
      let index = fileList2.findIndex(fileItem => {
        return fileItem.uid === fileList2.uid
      })
      this.fileList.splice(index - 1, 1)
    },
    handlePreview(file) {
    },
    // 上传附件超出5个时的提示
    handleExceed(files2, fileList2) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files2.length} 个文件，共选择了 ${files2.length + fileList2.length} 个文件`)
    },
    // 移除附件的确定
    beforeRemove(file2, fileList2) {
      return this.$confirm(`确定移除 ${file2.name}？`)
    },
    // 附件上传成功的回调
    handleSuccess(response2, file2, fileList2) {
      if (this.id !== undefined) {
        this.fileList.push({ name: response2.data.name, url: response2.data.url })
      } else {
        this.filListUpload.push({ name: response2.data.name, url: response2.data.url })
        this.fileList = this.filListUpload
      }
    },
    // 打开邮件配置的弹框
    handleSetting() {
      this.$refs.settingDialog.init(true)
    },
    // 存放草稿箱
    saveDrafts() {
      if (this.ruleForm.content) {
        var contentSave = this.ruleForm.content.replace(/class="ql-align-right"/g, 'style="text-align: right"')
          .replace(/class="ql-align-center"/g, 'style="text-align: center"')
          .replace(/class="ql-indent-1"/g, 'style="text-indent: 1rem"')
          .replace(/class="ql-align-right ql-direction-rtl"/g, 'style="text-align: right"')
          .replace(/class="ql-size-small"/g, 'style="font-size: 10px"')
          .replace(/class="ql-size-large"/g, 'style="font-size: 18px"')
          .replace(/class="ql-size-huge"/g, 'style="font-size: 32px"')
          // .replace(/\s/g, '&nbsp;')
      }
      const data = {
        id: this.id,
        user: this.ruleForm.user,
        title: this.ruleForm.title,
        content: contentSave,
        fileList: this.fileList
      }
      saveDrafts(data).then((res) => {
        if (res.code === 200) {
          this.ruleForm = {}
          this.fileList = []
          this.ruleForm.content = ''
        }
      })
    },
    // 点击按钮，弹出更多收件人
    handleContactsClick() {
      this.contactsDialogVisible = true
    },
    // 选中节点
    handleNodeClick(data, checkedNodes) {
      this.contactsArr = checkedNodes.checkedNodes.map(item => {
        return item.address
      })
      this.ruleForm.user = this.contactsArr.toString()
    },
    // 将字符串数组转换成正常数组
    evil(fn) {
      let Fn = Function // 一个变量指向Function，防止有些前端编译工具报错
      return new Fn('return ' + fn)()
    }
  }
}
</script>

<style scoped>
  .muban p {
    font-size: 24px;
    font-weight: 600;
    padding: 3px;
    border-bottom: #EEEEEE 1px solid;
    margin: 40px 0 40px 0;
  }
  .upLoad {
    margin-bottom: 0;
  }
  .upload-demo {
    display: flex;
  }
  .upload-demo li {
    margin-top: 0;
  }
  .upload-button:hover {
    text-decoration: underline;
  }
  .el-button-group {
    margin-bottom: 20px;
    margin-left: 80px;
  }
  .contacts_button {
    margin-left: 10px;
  }
</style>
